<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://unpkg.com/redux@4.2.0/dist/redux.js"></script>
</head>

<body>
  <h1>默认值</h1>
  <button>点击我增加</button>
  <button>点击我减少</button>
  <script>
    // 一、创建reducer 函数 
    /* 
    2个参数 
        第一个参数是state
        第二个参数是action
            action里有2个参数 ： 1.type action的类型  2. payload  或者是 data 是参数 ，可以用于传参
    
    */

    function reducer(state = { count: 1 }, action) {
      if (action.type === "add") {
        return { ...state, count: state.count + action.payload }
      }
      if (action.type === "minus") {
        return { ...state, count: state.count - action.payload }
      }
      return state;
    }


    let store = Redux.createStore(reducer);
    store.subscribe(() => {
      console.log("触发了");
      document.querySelector("h1").innerHTML = store.getState().count;
    })


    // 获取状态值 
    document.querySelector("h1").innerHTML = store.getState().count;

    // 通过 action来更改状态值；需要通过 dispatch来进行触发
    let btns = document.querySelectorAll("button");
    btns[0].onclick = function () {
      console.log(111);
      store.dispatch({ type: "add", payload: 2 })
      console.log(store.getState());
    }

    btns[1].onclick = function () {
      store.dispatch({ type: "minus", payload: 1 })
      console.log(store.getState());
    }







  </script>
</body>

</html>